package com.mc.book.utils.baidu;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * TODO 目前都是单任务执行，后续优化可以考虑并行
 * @Author
 * @Date 2024/6/30 上午 10:42
 */
public class BaiduText {
    private static final Logger log = LoggerFactory.getLogger(BaiduText.class);
    //    public static final String API_KEY = "hbz5ZzjoW4RzXLHnYzAj1oDp";
//    public static final String SECRET_KEY = "BnMFBC3SUC5FsYcuXtStthskoNh4NT4v";
    public static final String API_KEY = "IqB0f6yfXtxN4M2uSxdhQk3e";
    public static final String SECRET_KEY = "GM1JT2Lj93fA3bOIC8VFFIG89FFjEccv";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient();

    public static void main(String[] args) throws Exception {
        String file = "C:\\Users\\14910\\Desktop\\format.1719709984795.json";
        String out = "C:\\Users\\14910\\Desktop\\format.mp3";
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bs = new byte[fileInputStream.available()];
        fileInputStream.read(bs);
        System.out.println(getContentNow(new String(bs)));
//        fileInputStream.read(bs);
//        FileOutputStream fileOutputStream = new FileOutputStream(out);
//        fileOutputStream.write(Base64.decode(bs));
//        fileInputStream.close();
//        fileOutputStream.flush();
//        fileOutputStream.close();
//        System.out.println("aa啊");
//        String msgByFile = getMsgByFile("http://43.143.227.53:8999/book/profile/upload/2024/06/13/format.mp3");
//        String msgByFile = query("6680d3185d73020001d3bddf");
//        System.out.println(msgByFile);
    }

    /**
     * 获取内容
     * @param base64Str
     * @return java.lang.String
     * @Author dong
     * @Date 2024/6/30 下午 3:56
     */
    public static String getContentNow(String base64Str) {
        String result = null;
        JSONObject param = new JSONObject();
        try {
            MediaType mediaType = MediaType.parse("application/json");
            param.put("format", "wav");
            param.put("dev_pid", 80001);
            param.put("rate", 16000);
            param.put("channel", 1);
            param.put("cuid", "1234567JAVA");
            param.put("len", Base64.decode(base64Str).length);
            param.put("speech", base64Str);
            param.put("token", getAccessToken());

            RequestBody body = RequestBody.create(mediaType, param.toString());
            Request request = new Request.Builder()
                    .url("https://vop.baidu.com/pro_api")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = null;
            response = HTTP_CLIENT.newCall(request).execute();
            result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray jsonArray = jsonObject.getJSONArray("result");
            StringBuilder sb = new StringBuilder();
            for (Object o : jsonArray) {
                sb.append(o);
            }
            return sb.toString().trim();
        } catch (Exception e) {
            log.error("创建语音转文字任务失败！param={}, result={}", param, result, e);
        }
        return "识别失败！";
    }

    public static String getMsgByFile(String filePath) {
        String taskId = create(filePath);
        System.out.println(taskId);
        if (StrUtil.isNotEmpty(taskId)) {
            for (int i=0;i<1000;i++) {
                try {
                    Thread.sleep(1000);
                    String query = query(taskId);
                    System.out.println(i+"msg:"+query);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 创建语音转文字任务
     * @param filePath
     * @return java.lang.String
     * @Author dong
     * @Date 2024/6/30 上午 10:42
     */
    public static String create(String filePath) {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject param = new JSONObject();
        param.put("speech_url", filePath);
        param.put("format", filePath.substring(filePath.lastIndexOf(StrPool.DOT)+1));
        param.put("pid", 80001);
        param.put("rate", 16000);

        RequestBody body = RequestBody.create(mediaType, param.toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/create?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        String result = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            String taskId = jsonObject.getString("task_id");
            if (StrUtil.isEmpty(taskId)) {
                throw new RuntimeException(StrUtil.format("创建语音转文字任务失败！filePath={}, result={}", filePath, result));
            }
            return taskId;
        } catch (Exception e) {
            log.error("创建语音转文字任务失败！filePath={}, result={}", filePath, result, e);
        }
        return null;
    }

    /**
     * 查询任务信息
     * @param taskId
     * @return java.lang.String
     * @Author dong
     * @Date 2024/6/30 上午 10:42
     */
    public static String query(String taskId) {
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject param = new JSONObject();
        param.put("task_ids", Arrays.asList(taskId));
        RequestBody body = RequestBody.create(mediaType, param.toString());
        String accessToken = getAccessToken();
        System.out.println(accessToken);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/aasr/v1/query?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = null;
        String result = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
            result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject tasksInfo = jsonObject.getJSONArray("tasks_info").getJSONObject(0);
            if (!Objects.equals(tasksInfo.getString("task_status"), "Success")) {
                return null;
            }
            JSONArray jsonArray = tasksInfo.getJSONObject("task_result").getJSONArray("result");
            StringBuilder sb = new StringBuilder();
            for (Object o : jsonArray) {
                sb.append(o);
            }
            String trim = sb.toString().trim();
            return trim;
        } catch (IOException e) {
            log.error("查询语音转文字任务失败！taskId={}, result={}", taskId, result, e);
        }
        return null;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = null;
        try {
            response = HTTP_CLIENT.newCall(request).execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            return JSONObject.parseObject(response.body().string()).getString("access_token");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
